package com.ktgj.train.service.impl;

import com.ktgj.common.core.constant.CustomerConstants;
import com.ktgj.common.core.domain.R;
import com.ktgj.common.core.enums.TrainEnum;
import com.ktgj.common.core.utils.IdUtils;
import com.ktgj.customer.api.RemoteCustomerService;
import com.ktgj.customer.api.domain.*;
import com.ktgj.train.common.TrainTickets;
import com.ktgj.train.domain.InterfaceEntity.*;
import com.ktgj.train.domain.TrainAccount;
import com.ktgj.train.domain.TrainContacts;
import com.ktgj.train.domain.VerificationStatus;
import com.ktgj.train.service.TrainService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class TrainServiceImpl implements TrainService {

    @Autowired
    private TrainTickets trainTickets;

    @Autowired
    private RemoteCustomerService remoteCustomerService;

    @Override
    public TrContactQueryResponse passengerList(HttpServletRequest httpServletRequest, TrContactQueryRequest request) {
        TrContactQueryResponse response = new TrContactQueryResponse();
        try {
            R<Customer> loginCustomerByToken;
            if (request.customerId == null || request.customerId == 0){
                String token = httpServletRequest.getHeader("token");
                loginCustomerByToken = remoteCustomerService.getLoginCustomerByToken(token);
            }
            else {
                loginCustomerByToken = remoteCustomerService.getCustomerId(request.customerId);
            }

            if (loginCustomerByToken.getData().getTrainAccount() != null && loginCustomerByToken.getData().getTrainPassword() != null) {
                String trainAccount = loginCustomerByToken.getData().getTrainAccount();
                String trainPassword = loginCustomerByToken.getData().getTrainPassword();
                request.trainAccount = trainAccount;
                request.pass = trainPassword;
                response = trainTickets.contactQuery(request);
            }
        } catch (Exception e) {
            response.errorMsg = e.getMessage() + e.getStackTrace();
        }
        return response;
    }

    //增加和修改常用联系人
    @Override
    public TrAddAndUpdateContactsResponse addUpdatePassenger(HttpServletRequest httpServletRequest, TrAddAndUpdateContactsRequest request) {
        TrAddAndUpdateContactsResponse response = new TrAddAndUpdateContactsResponse();
        try {
            PassengerInformationApi information = new PassengerInformationApi();
            PassengerDocumentsApi passengerDocuments = new PassengerDocumentsApi();
            CommonTravelersApi commonTravelers = new CommonTravelersApi();
            if (request.contacts.personType == 0) {
                information.setTicketType("aldult");
                commonTravelers.setTicketType("aldult");
            } else if (request.contacts.personType == 1) {
                information.setTicketType("child");
                commonTravelers.setTicketType("child");
            }
            information.setChineseName(request.contacts.name);
            information.setDomesticPhone(request.contacts.phone);
            if (request.contacts.sex != null) {
                if (request.contacts.sex == 0) {
                    information.setGender("male");
                } else if (request.contacts.sex == 1) {
                    information.setGender("female");
                }
            }
            if (request.contacts.birthday != null && request.contacts.birthday != "") {
                information.setDateOfBirth(new Date(request.contacts.birthday));
            }
            if (request.contacts.country != null && request.contacts.country != "") {
                information.setNationality(request.contacts.country);
            }
            if (request.contacts.gatValidDateEnd != null && request.contacts.gatValidDateEnd != "") {
                passengerDocuments.setCertificateDate(request.contacts.gatValidDateEnd);
            }
            information.setNationality(request.contacts.country);
            if (request.contacts.identyType.equals("1")) {
                passengerDocuments.setCertificateType(TrainEnum.ID_CARD.getValue());
                passengerDocuments.setCertificateName("中国居民身份证");
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
                String cardNum = request.contacts.identy.substring(6, 14);
                Date parse = dateFormat.parse(cardNum);
                information.setDateOfBirth(parse);
            } else if (request.contacts.identyType.equals("2")) {
                passengerDocuments.setCertificateType(TrainEnum.RPFHKMATR.getValue());
                passengerDocuments.setCertificateName("港澳台居民居住证");
            } else if (request.contacts.identyType.equals("C")) {
                passengerDocuments.setCertificateType(TrainEnum.MTPFHKAMR.getValue());
                passengerDocuments.setCertificateName("港澳居民来往内地通行证");
            } else if (request.contacts.identyType.equals("G")) {
                passengerDocuments.setCertificateType(TrainEnum.MTPFTR.getValue());
                passengerDocuments.setCertificateName("台湾居民来往大陆通行证");
            } else if (request.contacts.identyType.equals("B")) {
                passengerDocuments.setCertificateType(TrainEnum.PASSPORT.getValue());
                passengerDocuments.setCertificateName("护照");
            } else if (request.contacts.identyType.equals("H")) {
                passengerDocuments.setCertificateType(TrainEnum.PRICFF.getValue());
                passengerDocuments.setCertificateName("外国人永久居留身份证");
            }
            passengerDocuments.setCertificateNumcer(request.contacts.identy);
            passengerDocuments.setCertificateDate(request.contacts.gatValidDateEnd);
            information.setPassengerDocuments(passengerDocuments);
            if (request.contacts.commonTrvelersId != null && request.contacts.commonTrvelersId != "") {
                commonTravelers.setCommonTrvelersId(Long.valueOf(request.contacts.commonTrvelersId));
                commonTravelers.setDomesticPhone(request.contacts.phone);
            }
            String token = httpServletRequest.getHeader("token");

            response = trainTickets.addAndUpdateContacts(request);
            /*for (PassengerVerification datum : response.data) {
                //if (request.contacts.id == 0 && datum.verify_status == 1) {
                if (request.contacts.id == 0) {
                    if (token != null && !token.equals("")){
                        remoteCustomerService.insertCommonTravelers(token, information);
                    }
                    else {
                        remoteCustomerService.insertCommonTravelersCrm(request.customerId, information);
                    }

                //} else if (request.contacts.id > 0 && datum.verify_status == 1 && request.contacts.commonTrvelersId != null && request.contacts.commonTrvelersId != "") {
                } else if (request.contacts.id > 0 && request.contacts.commonTrvelersId != null && request.contacts.commonTrvelersId != "") {
                    remoteCustomerService.edits(commonTravelers);
                }
            }*/
            if (request.contacts.id == 0) {
                if (token != null && !token.equals("")){
                    remoteCustomerService.insertCommonTravelers(token, information);
                }
                else {
                    remoteCustomerService.insertCommonTravelersCrm(request.customerId, information);
                }

                //} else if (request.contacts.id > 0 && datum.verify_status == 1 && request.contacts.commonTrvelersId != null && request.contacts.commonTrvelersId != "") {
            } else if (request.contacts.id > 0 && request.contacts.commonTrvelersId != null && request.contacts.commonTrvelersId != "") {
                remoteCustomerService.edits(commonTravelers);
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.errorMsg = e.getMessage() + e.getStackTrace();
        }
        /*if (response.returnCode == 239015 || response.errorMsg.equals("账号本人信息不允许修改")|| response.errorMsg.equals("该联系人已存在")) {
            response.success = true;
            response.errorMsg = "操作成功";
            response.returnCode = 231000;
        }*/
        return response;
    }

    @Override
    public Map<String, Object> pay(TrainPaymentRequest request) {
        TrainPaymentResponse response = trainTickets.trainPayment(request);
        Map<String, Object> map = new HashMap<>();
        map.put("price", response.getPrice());
        map.put("payLink", response.getPayLink());
        return map;
    }

    @Override
    public TrPayStatusSynchResponse payStatus(TrPayStatusSynchRequest request) {
        //TODO 刘健 接受支付回调判断是否支付成功
        TrPayStatusSynchResponse response = trainTickets.payStatusSynch(request);
        return response;
    }

    //找回密码（获取验证码）
    @Override
    public TrRetrievePasswordResponse retrievePassword(TrRetrievePasswordRequest request) {
        String uuid = IdUtils.randomUUID();
        request.data.requestid = uuid;
        TrRetrievePasswordResponse response = trainTickets.retrievePassword(request);
        response.requestid = uuid;
        return response;
    }

    //找回密码（回填验证码）
    @Override
    public TrRetrievePasswordResponse sendcaptcharesult(String token, TrRetrievePasswordRequest request) {
        TrRetrievePasswordResponse response = trainTickets.sendcaptcharesult(request);
        R<Customer> customerR;
        if (token != null && !token.equals("")){
            customerR = remoteCustomerService.getLoginCustomerByToken(token);
        }
        else {
            customerR = remoteCustomerService.getCustomerInfo(request.customerId);
        }
        if (customerR.getCode() == 200) {
            Long customerId = customerR.getData().getCustomerId();
            R<CustomeraccountApi> customeraccountApiR = remoteCustomerService.queryAccountIdAndAccountPassword(customerId, CustomerConstants.trianAccount.getValue());
            CustomeraccountApi customeraccountApi = new CustomeraccountApi();
            if (response.code == 1100 && customeraccountApiR.getCode() == 200 && customeraccountApiR.getData() != null) {
                customeraccountApi.setCustomerId(customerId);
                customeraccountApi.setAccountId(request.data.mobileNo);
                customeraccountApi.setAccountType(CustomerConstants.trianAccount.getValue());
                customeraccountApi.setAccountPassword(request.data.confirmPassword);
                remoteCustomerService.updateAccountPassword(customeraccountApi);
            } else if (response.code == 1100 && customeraccountApiR.getCode() == 200 && customeraccountApiR.getData() == null) {
                customeraccountApi.setAccountId(request.data.mobileNo);
                customeraccountApi.setAccountPassword(request.data.confirmPassword);
                customeraccountApi.setAccountType(CustomerConstants.trianAccount.getValue());
                customeraccountApi.setCustomerId(customerId);
                remoteCustomerService.insert(customeraccountApi);
            }
        }
        return response;
    }

    //重置密码（获取验证码）
    @Override
    public TrResetPasswordResponse resetPassword(TrResetPasswordRequest request) {
        TrResetPasswordResponse response = trainTickets.resetPassword(request);
        return response;
    }

    //重置密码（发送验证码）
    @Override
    public TrResetPasswordResponse resetPasswordSend(String token, TrResetPasswordRequest request) {
        TrResetPasswordResponse response = trainTickets.resetPasswordSend(request);
        R<Customer> customer = remoteCustomerService.getLoginCustomerByToken(token);
        if ("1001".equals(response.code) && customer.getCode() == 200) {
            CustomeraccountApi customeraccountApi = new CustomeraccountApi();
            customeraccountApi.setCustomerId(customer.getData().getCustomerId());
            customeraccountApi.setAccountType(CustomerConstants.trianAccount.getValue());
            customeraccountApi.setAccountPassword(request.confirmPassword);
            remoteCustomerService.updateAccountPassword(customeraccountApi);
        }
        return response;
    }

    //12306注册
    @Override
    public TrRegisterAccountResponse registerAccount(TrRegisterAccountRequest request) {
        return trainTickets.registerAccount(request);
    }

    //短信验证
    @Override
    public TrPhoneMessageValidateResponse phoneMessageValidate(Long customerId, TrPhoneMessageValidateRequest request) {
        TrPhoneMessageValidateResponse response = trainTickets.phoneMessageValidate(request);
        CustomeraccountApi customerAccount = new CustomeraccountApi();
        R<CustomeraccountApi> customeraccountApiR = remoteCustomerService.queryAccountIdAndAccountPassword(customerId, CustomerConstants.trianAccount.getValue());
        if (customeraccountApiR.getCode() == 200 && customeraccountApiR.getData() != null) {
            if (response.success.equals(true)) {
                customerAccount.setAccountId(request.userName);
                customerAccount.setAccountPassword(request.passWord);
                customerAccount.setAccountType(CustomerConstants.trianAccount.getValue());
                customerAccount.setCustomerId(customerId);
                customerAccount.setCreateTime(new Date());
                remoteCustomerService.updateAccountPassword(customerAccount);
            }
        } else if (customeraccountApiR.getCode() == 200 && customeraccountApiR.getData() == null && request.validateType == 2) {
            if (response.success.equals(true)) {
                customerAccount.setAccountId(request.userName);
                customerAccount.setAccountPassword(request.passWord);
                customerAccount.setAccountType(CustomerConstants.trianAccount.getValue());
                customerAccount.setCustomerId(customerId);
                customerAccount.setCreateTime(new Date());
                remoteCustomerService.insert(customerAccount);
            }
        }
        return response;
    }

    /**
     * 查询12306账号
     * @param customerId
     * @return
     */
    @Override
    public TrainAccount queryAccountId(Long customerId) {
        TrainAccount trainAccount = new TrainAccount();
        R<CustomeraccountApi> customeraccountApiR = remoteCustomerService.queryAccountIdAndAccountPassword(customerId, CustomerConstants.trianAccount.getValue());
        if (customeraccountApiR.getCode() == 200 && customeraccountApiR.getData() != null) {
            trainAccount.setAccountId(customeraccountApiR.getData().getAccountId());
            trainAccount.setAccountPassword(customeraccountApiR.getData().getAccountPassword());
        }
        return trainAccount;
    }

    //联系方式核验
    @Override
    public int verificationStatus(VerificationStatus status) {
        TrContactQueryRequest request = new TrContactQueryRequest();
        request.trainAccount = status.getTrainAccount();
        request.pass = status.getPass();
        TrContactQueryResponse response = trainTickets.contactQuery(request);
        int phoneCheckStatus = 1;
        if (response.success) {
            if (response.data != null && response.data.size() > 0) {
                for (TrainContacts datum : response.data) {
                    if (status.getIdenty().substring(0, 4).equals(datum.getIdenty().substring(0, 4)) && status.getIdenty().substring(status.getIdenty().length() - 3).equals(datum.getIdenty().substring(datum.getIdenty().length() - 3))) {
                        if (datum.getPhoneCheckStatus().equals("0")) {
                            phoneCheckStatus = 0;
                        }
                    }
                }
            }
        }

        return phoneCheckStatus;
    }
}
